package com.haotian.coder.service.Impl;

import cn.hutool.core.util.ZipUtil;
import com.haotian.coder.exception.BusinessException;
import com.haotian.coder.exception.ErrorCode;
import com.haotian.coder.exception.ThrowUtils;
import com.haotian.coder.service.ProjectDownloadService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileFilter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Set;


@Service
@Slf4j
public class ProjectDownloadServiceImpl  implements ProjectDownloadService {


    /**
     * 需要过滤的文件和目录名称
     */
    private static final Set<String>  IGNORE_NAMES = Set.of(
           "node_modules",
           ".git",
           "dist",
           "build",
           ".DS_Store",
           ".env",
           "target",
           ".mvn",
           ".idea",
           ".vscode"
   );

    /**
     * 需要过滤的文件扩展名
     */
    private static final Set<String>  IGNORE_EXTENSIONS = Set.of(
          ".log",
          ".tmp",
          ".cache"
    );


    private boolean isPathAllow(Path projectPath, Path fullPath) {
        // 获取相对路径
        Path relativePath = projectPath.relativize(fullPath);
        // 检查路径中的每一部分
        for (Path path : relativePath) {
            String partName = path.toString();
            if (IGNORE_NAMES.contains(partName)) {
                return false;
            }
            if (IGNORE_EXTENSIONS.stream().anyMatch(partName::endsWith)) {
                ;
                return false;
            }
        }
        return true;
    }





    @Override
    public void downloadProjectAsZip(String projectPath, String downloadFilename, HttpServletResponse response){
        // 基础校验
        ThrowUtils.throwIf(projectPath==null, ErrorCode.PARAMS_ERROR,"路径错误");
        ThrowUtils.throwIf(downloadFilename==null, ErrorCode.PARAMS_ERROR,"文件名错误");
        File projectDir = new File(projectPath);
        ThrowUtils.throwIf(!projectDir.exists(), ErrorCode.PARAMS_ERROR,"文件不存在");
        ThrowUtils.throwIf(!projectDir.isDirectory(), ErrorCode.PARAMS_ERROR,"不是一个文件");
        // 设置http响应头
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/zip");
        response.addHeader("Content-Disposition",
                String.format(("attachment;filename=\"%s.zip\""),downloadFilename));
        // 过滤文件
        FileFilter fileFilter =file ->isPathAllow(projectDir.toPath(),file.toPath());
        // 打包
        try {
            ZipUtil.zip(response.getOutputStream(), StandardCharsets.UTF_8,false,fileFilter,projectDir);
            log.info("项目打包下载完成:{}",downloadFilename);
        } catch (Exception e) {
            log.error("项目打包下载");
            throw  new BusinessException(ErrorCode.SYSTEM_ERROR,"项目打包下载");
        }
    }
}
